<template>
  <div class="min-h-screen bg-gradient-to-b from-blue-900 via-indigo-900 to-purple-900 flex items-center justify-center p-4">
    <!-- 返回按钮 -->
    <button 
      @click="$router.push('/')" 
      class="absolute top-4 left-4 text-white hover:text-blue-300 transition-colors duration-300 flex items-center gap-2"
    >
      <span class="text-2xl">←</span>
      <span class="text-lg">返回游戏大厅</span>
    </button>

    <div class="w-full max-w-4xl bg-white/10 backdrop-blur-lg rounded-2xl shadow-2xl overflow-hidden border border-white/20">
      <div class="p-8">
        <h1 class="text-5xl font-bold text-center text-white mb-8 animate-title">
          唐诗益智游戏
          <div class="text-lg font-normal mt-2 text-white/80">测试你的唐诗知识，享受诗词之美</div>
        </h1>
        
        <transition name="fade" mode="out-in">
          <div v-if="!gameStarted && !learningMode" key="menu" class="space-y-8">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div class="game-option-card">
                <label for="difficulty" class="block text-lg font-medium text-white mb-2">难度选择：</label>
                <select 
                  id="difficulty" 
                  v-model="difficulty" 
                  class="w-full p-3 bg-white/10 border border-white/20 rounded-lg text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"
                >
                  <option value="easy">简单</option>
                  <option value="medium">中等</option>
                  <option value="hard">困难</option>
                </select>
              </div>
              
              <div class="game-option-card">
                <label class="block text-lg font-medium text-white mb-2">游戏模式：</label>
                <div class="space-y-3">
                  <label class="flex items-center text-white cursor-pointer hover:text-blue-300 transition-colors">
                    <input type="radio" v-model="gameMode" value="all" class="mr-3 w-4 h-4">
                    <span>所有诗歌</span>
                  </label>
                  <label class="flex items-center text-white cursor-pointer hover:text-blue-300 transition-colors">
                    <input type="radio" v-model="gameMode" value="custom" class="mr-3 w-4 h-4">
                    <span>自定义选择</span>
                  </label>
                </div>
              </div>
            </div>
            
            <transition name="slide-fade">
              <div v-if="gameMode === 'custom'" class="game-option-card">
                <label class="block text-lg font-medium text-white mb-2">选择诗歌：</label>
                <div class="h-48 overflow-y-auto custom-scrollbar">
                  <label 
                    v-for="poem in poems" 
                    :key="poem.title" 
                    class="flex items-center p-2 text-white hover:bg-white/10 rounded transition-colors cursor-pointer"
                  >
                    <input type="checkbox" v-model="selectedPoems" :value="poem.title" class="mr-3 w-4 h-4">
                    <span>{{ poem.title }} - {{ poem.author }}</span>
                  </label>
                </div>
              </div>
            </transition>
            
            <div class="flex flex-col sm:flex-row gap-4 justify-center">
              <button 
                @click="startGame" 
                class="game-button bg-gradient-to-r from-blue-500 to-blue-700"
              >
                开始游戏
              </button>
              <button 
                @click="startLearningMode" 
                class="game-button bg-gradient-to-r from-purple-500 to-purple-700"
              >
                学习模式
              </button>
            </div>

            <!-- 统计信息卡片 -->
            <div class="stats-card">
              <h3 class="text-2xl font-bold text-white mb-4">游戏统计</h3>
              <div class="grid grid-cols-2 gap-6">
                <div class="stat-item">
                  <div class="text-3xl font-bold text-blue-400">{{ highScore }}</div>
                  <div class="text-sm text-white/80">最高分</div>
                </div>
                <div class="stat-item">
                  <div class="text-3xl font-bold text-purple-400">{{ averageScore.toFixed(1) }}</div>
                  <div class="text-sm text-white/80">平均分</div>
                </div>
                <div class="stat-item">
                  <div class="text-3xl font-bold text-green-400">{{ gamesPlayed }}</div>
                  <div class="text-sm text-white/80">游戏次数</div>
                </div>
                <div class="stat-item">
                  <div class="text-3xl font-bold text-yellow-400">{{ totalAnswered }}</div>
                  <div class="text-sm text-white/80">总答题数</div>
                </div>
              </div>
            </div>
          </div>

          <div v-else-if="gameStarted" key="game" class="space-y-6">
            <div class="text-center">
              <h2 class="text-2xl font-bold text-white mb-2">{{ currentPoem.title }}</h2>
              <p class="text-lg text-white/80 mb-4">作者：{{ currentPoem.author }}</p>
              <p class="text-xl text-white mb-4 poem-line">{{ currentPoem.lines[currentLine] }}</p>
              <p class="text-lg text-blue-300 mb-4">请选择下一句：</p>
            </div>
            
            <transition-group name="list" tag="div" class="space-y-3">
              <button
                v-for="option in options"
                :key="option"
                @click="handleAnswer(option)"
                class="w-full text-left bg-white/10 border border-white/20 rounded-lg py-3 px-4 text-white hover:bg-white/20 transition duration-300"
              >
                {{ option }}
              </button>
            </transition-group>
            
            <div class="flex justify-between items-center">
              <p class="text-lg text-white">得分：{{ score }}/{{ totalQuestions }}</p>
              <p class="text-lg text-white">时间：{{ formatTime(timer) }}</p>
            </div>
            
            <button 
              @click="endGame" 
              class="game-button bg-gradient-to-r from-red-500 to-red-700 w-full"
            >
              结束游戏
            </button>
          </div>

          <div v-else-if="learningMode" key="learning" class="space-y-6">
            <div class="bg-white/10 rounded-lg p-6">
              <h2 class="text-2xl font-bold text-white mb-2">{{ currentPoem.title }}</h2>
              <p class="text-lg text-white/80 mb-4">作者：{{ currentPoem.author }}</p>
              <transition-group name="list" tag="div" class="space-y-4">
                <div v-for="(line, index) in currentPoem.lines" :key="index">
                  <p class="text-xl text-white poem-line">{{ line }}</p>
                  <p v-if="currentPoem.annotations && currentPoem.annotations[index]" 
                     class="text-sm text-white/70 ml-4 mt-1">
                    注释：{{ currentPoem.annotations[index] }}
                  </p>
                </div>
              </transition-group>
            </div>
            
            <div class="flex justify-between gap-4">
              <button 
                @click="prevPoem" 
                class="game-button bg-gradient-to-r from-gray-600 to-gray-700"
              >
                上一首
              </button>
              <button 
                @click="nextPoem" 
                class="game-button bg-gradient-to-r from-gray-600 to-gray-700"
              >
                下一首
              </button>
            </div>
            
            <button 
              @click="exitLearningMode" 
              class="game-button bg-gradient-to-r from-blue-500 to-blue-700 w-full"
            >
              返回主菜单
            </button>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'

const poems = [
  {
    title: '静夜思',
    author: '李白',
    lines: ['床前明月光，', '疑是地上霜。', '举头望明月，', '低头思故乡。'],
    annotations: [
      '诗人在床前看到了明亮的月光。',
      '诗人起初以为是地上的霜。',
      '诗人抬头看到了明月。',
      '诗人低头时想到了远方的家乡。'
    ]
  },
  {
    title: '春晓',
    author: '孟浩然',
    lines: ['春眠不觉晓，', '处处闻啼鸟。', '夜来风雨声，', '花落知多少。'],
    annotations: [
      '诗人在春天睡得很沉，不知不觉天就亮了。',
      '醒来后，诗人听到到处都是鸟儿的叫声。',
      '昨晚有风有雨。',
      '诗人猜想不知道有多少花儿因为风雨而凋落。'
    ]
  },
  {
    title: '登鹳雀楼',
    author: '王之涣',
    lines: ['白日依山尽，', '黄河入海流。', '欲穷千里目，', '更上一层楼。'],
    annotations: [
      '太阳正要落山。',
      '黄河流向大海。',
      '想要看得更远。',
      '就要再登高一层。'
    ]
  },
  // 可以继续添加更多诗歌...
]

const difficulty = ref('medium')
const gameMode = ref('all')
const selectedPoems = ref([])
const gameStarted = ref(false)
const learningMode = ref(false)
const currentPoem = ref(null)
const currentLine = ref(0)
const options = ref([])
const score = ref(0)
const totalQuestions = ref(0)
const timer = ref(0)
const timerInterval = ref(null)

// 统计信息
const highScore = ref(0)
const totalScore = ref(0)
const gamesPlayed = ref(0)
const totalAnswered = ref(0)

const averageScore = computed(() => {
  return gamesPlayed.value > 0 ? totalScore.value / gamesPlayed.value : 0
})

const availablePoems = computed(() => {
  if (gameMode.value === 'all') return poems
  return poems.filter(poem => selectedPoems.value.includes(poem.title))
})

const startGame = () => {
  if (gameMode.value === 'custom' && selectedPoems.value.length === 0) {
    alert('请至少选择一首诗歌')
    return
  }
  gameStarted.value = true
  score.value = 0
  totalQuestions.value = 0
  timer.value = 0
  startTimer()
  nextQuestion()
}

const startTimer = () => {
  timerInterval.value = setInterval(() => {
    timer.value++
  }, 1000)
}

const stopTimer = () => {
  clearInterval(timerInterval.value)
}

const formatTime = (time) => {
  const minutes = Math.floor(time / 60)
  const seconds = time % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const nextQuestion = () => {
  const randomPoem = availablePoems.value[Math.floor(Math.random() * availablePoems.value.length)]
  currentPoem.value = randomPoem
  currentLine.value = Math.floor(Math.random() * (randomPoem.lines.length - 1))
  generateOptions()
  totalQuestions.value++
}

const generateOptions = () => {
  const correctAnswer = currentPoem.value.lines[currentLine.value + 1]
  let incorrectOptions
  if (difficulty.value === 'easy') {
    incorrectOptions = getRandomLines(2)
  } else if (difficulty.value === 'medium') {
    incorrectOptions = getRandomLines(3)
  } else {
    incorrectOptions = getRandomLines(4)
  }
  options.value = [correctAnswer, ...incorrectOptions].sort(() => Math.random() - 0.5)
}

const getRandomLines = (count) => {
  const lines = []
  while (lines.length < count) {
    const randomPoem = poems[Math.floor(Math.random() * poems.length)]
    const randomLine = randomPoem.lines[Math.floor(Math.random() * randomPoem.lines.length)]
    if (!lines.includes(randomLine) && randomLine !== currentPoem.value.lines[currentLine.value + 1]) {
      lines.push(randomLine)
    }
  }
  return lines
}

const handleAnswer = (selectedAnswer) => {
  if (selectedAnswer === currentPoem.value.lines[currentLine.value + 1]) {
    score.value++
  }
  totalAnswered.value++
  if (totalQuestions.value < 10) {
    nextQuestion()
  } else {
    endGame()
  }
}

const endGame = () => {
  stopTimer()
  gameStarted.value = false
  gamesPlayed.value++
  totalScore.value += score.value
  if (score.value > highScore.value) {
    highScore.value = score.value
  }
  alert(`游戏结束！你的得分是：${score.value}/${totalQuestions.value}，用时：${formatTime(timer.value)}`)
  saveGameData()
}

const startLearningMode = () => {
  learningMode.value = true
  currentPoem.value = poems[0]
}

const exitLearningMode = () => {
  learningMode.value = false
}

const nextPoem = () => {
  const currentIndex = poems.findIndex(poem => poem.title === currentPoem.value.title)
  if (currentIndex < poems.length - 1) {
    currentPoem.value = poems[currentIndex + 1]
  }
}

const prevPoem = () => {
  const currentIndex = poems.findIndex(poem => poem.title === currentPoem.value.title)
  if (currentIndex > 0) {
    currentPoem.value = poems[currentIndex - 1]
  }
}

const saveGameData = () => {
  localStorage.setItem('poemGameData', JSON.stringify({
    highScore: highScore.value,
    totalScore: totalScore.value,
    gamesPlayed: gamesPlayed.value,
    totalAnswered: totalAnswered.value,
    difficulty: difficulty.value,
    gameMode: gameMode.value,
    selectedPoems: selectedPoems.value
  }))
}

const loadGameData = () => {
  const data = JSON.parse(localStorage.getItem('poemGameData'))
  if (data) {
    highScore.value = data.highScore
    totalScore.value = data.totalScore
    gamesPlayed.value = data.gamesPlayed
    totalAnswered.value = data.totalAnswered
    difficulty.value = data.difficulty
    gameMode.value = data.gameMode
    selectedPoems.value = data.selectedPoems
  }
}

watch([highScore, totalScore, gamesPlayed, totalAnswered, difficulty, gameMode, selectedPoems], saveGameData)

onMounted(loadGameData)
</script>

<style scoped>
.animate-title {
  animation: titleAnimation 1s ease-out;
}

@keyframes titleAnimation {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

.game-option-card {
  @apply bg-white/5 rounded-lg p-4 border border-white/10;
}

.game-button {
  @apply px-6 py-3 text-white font-bold rounded-lg shadow-lg hover:scale-105 transition duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500;
}

.stats-card {
  @apply bg-white/5 rounded-lg p-6 border border-white/10;
}

.stat-item {
  @apply text-center p-4 bg-white/5 rounded-lg border border-white/10;
}

.poem-line {
  @apply font-poetry tracking-wider;
}

.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-10px);
  opacity: 0;
}

.list-enter-active,
.list-leave-active {
  transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@font-face {
  font-family: 'Poetry';
  src: url('/fonts/poetry.ttf') format('truetype');
}

.font-poetry {
  font-family: 'Poetry', serif;
}
</style>